﻿$("#ResultContainer").prepend($("<mark/>").html("Page load event fired"));

$(document).on("click", "a", function (event) {
    /// <summary>
    ///     Assign click event for all available hyperlinks for load content via Ajax 
    /// </summary>
    event.preventDefault();
    var navigationPath = $(this).attr("href");
    loadContent(navigationPath);
    updateLocation(navigationPath);
});
onLocationChanged();

function loadContent(url) {
    /// <summary>
    ///     Load content from given location via Ajax request.
    /// </summary>
    /// <param name="url" type="String">Location of the new content</param>
    $.ajax({
        url: url,
        type: 'GET',
        contentType: "text/html; charset=utf-8",
        dataType: "html",
        success: function (responseData) {
            $("#ResultContainer").html($("#ResultContainer", responseData).html());
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert(jqXHR.status + " : " + errorThrown);
        }
    });
}

function updateLocation(relatedPath) {
    /// <summary>
    ///     Update the URL for new content without reloading the page
    /// </summary>
    /// <param name="relatedPath" type="String">Path foe updating location</param>
    if ("pushState" in history) {
        // use window.history.pushState if it support by the browser
        var currentPath = relatedPath ? { navigationPath: relatedPath} : "";
        window.history.pushState(currentPath, document.title, "/" + relatedPath);
    } else {
        // use hash as fallback option
        window.location.hash = relatedPath;
    }
}

function onLocationChanged() {
    /// <summary>
    ///     Register event handler for location change. 
    ///     This is used to load content when browser back button pressed
    /// </summary>
    if ("pushState" in history) {
        $(window).on("popstate", function (e) {
            var state = e.originalEvent.state;
            if (state && state.navigationPath) {
                var contentPath = state.navigationPath;
                loadContent(contentPath);
            }
        });
    }
    else {
        $(window).on('hashchange', function () {
            $href = $(window.location).attr("hash");
            loadContent($href.replace("#", ""));
        });
    }
}
